import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QGraphicsView, QGraphicsScene, QGraphicsPixmapItem
from PyQt6.QtGui import QPixmap, QPainter, QPen, QColor
from PyQt6.QtCore import Qt, QRectF, QRect, QPointF


class ImageViewer(QGraphicsView):
	def __init__(self):
		super().__init__()

		self.image_path = "2.png"
		self.image_scale = 1.0

		self.scene = QGraphicsScene()
		self.setScene(self.scene)

		self.pixmap_item = QGraphicsPixmapItem()
		self.scene.addItem(self.pixmap_item)

		self.rect_item = None
		self.selection_rect = None
		self.start_pos = None

		self.setup_ui()
		self.load_image()

	def setup_ui(self):
		self.setWindowTitle("Image Viewer")
		self.setGeometry(100, 100, 800, 600)

	def load_image(self):
		pixmap = QPixmap(self.image_path)
		self.pixmap_item.setPixmap(pixmap)
		self.setSceneRect(0, 0, pixmap.width(), pixmap.height())

	def draw_selection_rect(self):
		if self.rect_item:
			self.scene.removeItem(self.rect_item)

		self.rect_item = self.scene.addRect(self.selection_rect, pen=QPen(QColor("green")))
		print("Top-left corner:", self.selection_rect.topLeft().x(), self.selection_rect.topLeft().y())
		print("Bottom-right corner:", self.selection_rect.bottomRight().x(), self.selection_rect.bottomRight().y())

	def mousePressEvent(self, event):
		if event.buttons() == Qt.MouseButton.LeftButton:
			self.start_pos = event.pos()
			self.selection_rect = QRectF(QPointF(self.start_pos), QPointF(self.start_pos))
			self.draw_selection_rect()

	def mouseMoveEvent(self, event):
		if event.buttons() == Qt.MouseButton.LeftButton and self.start_pos:
			end_pos = event.pos()
			self.selection_rect = QRectF(QPointF(self.start_pos), QPointF(end_pos)).normalized()
			self.draw_selection_rect()

	def mouseReleaseEvent(self, event):
		if event.button() == Qt.MouseButton.LeftButton:
			self.start_pos = None

	def wheelEvent(self, event):
		delta = event.angleDelta().y() / 240
		factor = 1.1 if delta > 0 else 0.9
		self.scale(factor, factor)

if __name__ == "__main__":
	app = QApplication(sys.argv)
	viewer = ImageViewer()
	viewer.show()
	sys.exit(app.exec())
